$(function () {
    $('input.product_id').attr('maxlength', 10);
    $('select.product_category_one').change(function () {
        $(this).parent().next().find('select.product_category_two').load("/admin/ajax/cate/" + $(this).val());
        $(this).parent().next().next().find('select.product_category_three').empty();
    });
    $('select.product_category_two').change(function () {
        $(this).parent().next().find('select.product_category_three').load("/admin/ajax/cate/" + $(this).val());
    });
    $('select[name="product_category_id_1"]').change(function () {
        $('select[name="product_category_id_2"]').load("/admin/ajax/cate/" + $(this).val());
        $('select[name="product_category_id_3"]').empty();
    });
    $('select[name="product_category_id_2"]').change(function () {
        $('select[name="product_category_id_3"]').load("/admin/ajax/cate/" + $(this).val());
    });
});

function batchDelete() {
    var ids = []
    $('.grid-row-checkbox').each(function (index, element) {
        if ($(element).is(':checked')) {
            ids.push($(element).attr('data-id'))
        }
    })
    if (ids.length === 0) return swal('请选择您要删除的商品', '', 'error')
    swal({
        type: 'warning',
        title: '确定要删除吗?',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: "取消",
    }).then((isConfirm) => {
        if (isConfirm.value === true) {
            adminAjax('ajax/batch', href(), {
                table: 'shopProduct',
                name: 'delete',
                ids: ids
            })
        }
    })
}

function batchDown() {
    var ids = []
    $('.grid-row-checkbox').each(function (index, element) {
        if ($(element).is(':checked')) {
            ids.push($(element).attr('data-id'))
        }
    })
    if (ids.length === 0) return swal('请选择您要下架的商品', '', 'error')
    swal({
        type: 'warning',
        title: '确定要下架吗?',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: "取消",
    }).then((isConfirm) => {
        if (isConfirm.value === true) {
            adminAjax('ajax/batch', href(), {
                table: 'shopProduct',
                name: 'down',
                ids: ids
            })
        }
    })
}

function batchUp() {
    const ids = []
    $('.grid-row-checkbox').each(function (index, element) {
        if ($(element).is(':checked')) {
            ids.push($(element).attr('data-id'))
        }
    })
    if (ids.length === 0) return swal('请选择您要上架的商品', '', 'error')
    swal({
        type: 'warning',
        title: '确定要上架吗?',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: "取消",
    }).then((isConfirm) => {
        if (isConfirm.value === true) {
            adminAjax('ajax/batch', href(), {
                table: 'shopProduct',
                name: 'up',
                ids: ids
            })
        }
    })
}

function editStock(t, method) {
    const currentRow = $(t).parents('tr')[0]
    const addBtn = $(currentRow).find('.add-btn')
    const subBtn = $(currentRow).find('.sub-btn')
    const currentStock = $(currentRow).find('.current-stock')
    const inputStock = $(currentRow).find('.edit-stock-input')
    const oldStock = $(currentRow).find('.old_stock').val()
    const activeClass = 'btn-primary'
    const defaultClass = 'btn-default'

    const methods = {
        'add': () => {
            subBtn.addClass(defaultClass).removeClass(activeClass)
            addBtn.addClass(activeClass).removeClass(defaultClass)
            currentStock.val(Number(oldStock) + Number(inputStock.val()))
        },
        'sub': () => {
            addBtn.addClass(defaultClass).removeClass(activeClass)
            subBtn.addClass(activeClass).removeClass(defaultClass)
            currentStock.val(Number(oldStock) - Number(inputStock.val()))
        },
        'inputChange': () => {
            if ($(currentRow).find('.btn-primary').html() === '增') {
                currentStock.val(Number(oldStock) + Number(inputStock.val()))
            } else if ($(currentRow).find('.btn-primary').html() === '减') {
                currentStock.val(Number(oldStock) - Number(inputStock.val()))
            }
        },
        'stockChange': () => {
            const newStock = currentStock.val() - oldStock
            if (newStock > 0) {
                subBtn.addClass(defaultClass).removeClass(activeClass)
                addBtn.addClass(activeClass).removeClass(defaultClass)
            } else if (newStock < 0) {
                addBtn.addClass(defaultClass).removeClass(activeClass)
                subBtn.addClass(activeClass).removeClass(defaultClass)
            } else {
                subBtn.addClass(defaultClass).removeClass(activeClass)
                addBtn.addClass(defaultClass).removeClass(activeClass)
            }
            inputStock.val(Math.abs(newStock))
            if (Math.abs(newStock) == oldStock) inputStock.val(Math.abs(newStock + 1))
        }
    }

    methods[method] && methods[method]()
    if (currentStock.val() <= 1) {
        currentStock.val(1)
    }
}

function saveEditStock(serialNumber, newAuth) {
    const params = {
        serialNumber,
        stock: {}
    }
    $('.stock-tr-list' + serialNumber).each(function (_, element) {
        const ps_id = $(element).find('.ps_id').val()
        params.stock[ps_id] = $(element).find('.current-stock').val()
    })
    apiAjax('shopProductSpec/editStock', href(), newAuth, params)
}

function batchPrice(t) {
    const priceRows = $(t).parent().parent().next().find('.spec-price-tr')
    const currentModal = priceRows.parent().parent().parent()
    const batchPriceUnderlined = currentModal.find('.batchPriceUnderlined').val()
    const batchPrice = currentModal.find('.batchPrice').val()
    const priceSelectVal = currentModal.find('.priceSelect').val() * 1

    if (priceSelectVal === 0) {
        if (batchPriceUnderlined.length === 0) return
        else if (batchPriceUnderlined === 0) return
        priceRows.each(function (_, element) {
            $(element).find('.marketPrice').val(batchPriceUnderlined)
            batchPrice && $(element).find('.price').val(batchPrice)
        })
    } else if (priceSelectVal === 1) {
        priceRows.each(function (_, element) {
            $(element).find('.marketPrice').val(batchPriceUnderlined * 1 + $(element).find('.old-under').val() * 1)
            batchPrice && $(element).find('.price').val(batchPrice * 1 + $(element).find('.old-price').val() * 1)
        })
    } else if (priceSelectVal === 2) {
        priceRows.each(function (_, element) {
            $(element).find('.marketPrice').val($(element).find('.old-under').val() * 1 - batchPriceUnderlined * 1)
            batchPrice && $(element).find('.price').val($(element).find('.old-price').val() * 1 - batchPrice * 1)
            if ($(element).find('.marketPrice').val() * 1 <= 0) $(element).find('.marketPrice').val(0)
            if ($(element).find('.price').val() * 1 <= 0) $(element).find('.price').val(0)
        })
    }
}

function saveSpecPrice(serialNumber, newAuth) {
    const priceData = {}
    let priceValid = true
    let priceLessUnder = true
    $(`#${serialNumber} .spec-price-tr`).each(function (_, element) {
        const price = $(element).find('input.price').val()
        const marketPrice = $(element).find('input.marketPrice').val()
        const psId = $(element).find('input.spec-price-hidden').val()
        marketPrice * 1 <= 0 && (priceValid = false)
        price * 1 >= marketPrice * 1 && (priceLessUnder = false)
        priceData[psId] = {
            psId,
            price,
            marketPrice,
        }
    })
    if (!priceValid) return swal('请输入正确的价格', '', 'error')
    if (!priceLessUnder) return swal('优惠价格需要小于原价', '', 'error')
    apiAjax('shopProductSpec/editPrice', href(), newAuth, {
        serialNumber: serialNumber,
        price: priceData
    })
}

function href() {
    const status = getQueryString('status')
    if (status === null) return 'shopProduct'
    else return 'shopProduct?status=' + status
}

// function initStyle() {
//     $('.box-header .pull-left').css({
//         'width': '100%',
//         'display': 'flex'
//     });
//     $('.box-header .pull-left .btn-group:eq(-5)').before('<div style="flex:1"></div>');
// }

// initStyle();
